package android.apps.bll;

import java.io.FileInputStream;

/**
 * Created by Andrew on 2015/12/28.
 */
public class RawBLL {
    public static final int LEPTON_WIDTH  = 160;
    public static final int LEPTON_HEIGHT = 120;

    byte[] rawBuffer = new byte[LEPTON_WIDTH*LEPTON_HEIGHT*2];
    public int[] rgbBuffer = new int[LEPTON_HEIGHT*LEPTON_WIDTH];
    float[] tempBuffer = new float[LEPTON_WIDTH*LEPTON_HEIGHT];
    int maxGray = 0; //最大灰度
    int minGray = 0; //最小灰度

    public RawBLL(String file)
    {
        try{
            FileInputStream fin = new FileInputStream(file);
//            int length = fin.available();
//            byte [] buffer = new byte[length];
            fin.read(rawBuffer);
            fin.close();

            int gray = (rawBuffer[0] << 8) | rawBuffer[1];
            maxGray = minGray = gray;
            for(int i=0;i<LEPTON_HEIGHT*LEPTON_WIDTH;i++)
            {
                gray = (rawBuffer[2*i] << 8) | rawBuffer[2*i+1];
                if(gray > maxGray){
                    maxGray = gray;
                }
                if(gray < minGray){
                    minGray = gray;
                }
            }
            for(int i=0;i<LEPTON_HEIGHT*LEPTON_WIDTH;i++) {
                gray = (rawBuffer[2 * i] << 8) | rawBuffer[2 * i + 1];
                byte byTmp = (byte) ( (gray - minGray) * 255 / (maxGray - minGray) );
                rgbBuffer[i] = (0x7F << 24) | (byTmp << 16) | (byTmp << 8) | byTmp;
                tempBuffer[i] = calcTemperature(gray);
            }
        }

        catch(Exception e){
            e.printStackTrace();
        }


    }

    float calcTemperature(int gray)
    {
        return (float) (((gray & 0xFF00)>>8) + (gray&0xFF) * 0.001);
    }

    public float getTemp(int y,int x)
    {
        if(0 <= x && LEPTON_WIDTH > x && 0 <=y && LEPTON_HEIGHT > y)
        {
            return tempBuffer[x * LEPTON_WIDTH + y];//报错；；；ArrayIndexOutOfBoundsException: length=19200; index=19936
        }
        return 0;
    }
}
